package xyz.lilei23.framework.transaction;

import xyz.lilei23.framework.annotation.Transactional;
import xyz.lilei23.framework.aop.AbstractAutoProxyCreator;
import xyz.lilei23.framework.aop.ProxyFactory;
import xyz.lilei23.framework.core.BeanFactory;

import java.lang.reflect.Method;

/**
 * 事务自动代理
 * @author lilei
 * @date 31/07/2021 16:20
 * @version 1.0
 **/
public class TransactionAutoProxyCreator extends AbstractAutoProxyCreator {

    public ProxyFactory proxyFactory;

    public BeanFactory beanFactory;

    public TransactionAutoProxyCreator(ProxyFactory proxyFactory, BeanFactory beanFactory) {
        this.proxyFactory = proxyFactory;
        this.beanFactory = beanFactory;
    }

    @Override
    public Object postProcessAfterInitialization(Object bean, String beanName) throws RuntimeException {
        if (!beanFactory.isEnableTransaction()){
            return bean;
        }
        Method[] methods = bean.getClass().getMethods();
        for (Method method : methods) {
            Transactional annotation = method.getAnnotation(Transactional.class);
            if (annotation != null){
                return proxyFactory.getCglibProxy(bean,TransactionMethodInterceptor.getInstance((TransactionManager) beanFactory.getBean(TransactionManager.class)));
            }
        }
        return bean;
    }

    @Override
    public int getOrder() {
        // 最后加载的初始化类 在代理类追加一个代理
        return Integer.MAX_VALUE;
    }
}
